package com.titleevaluation.config;

import com.titleevaluation.entity.Permission;
import com.titleevaluation.entity.Role;
import com.titleevaluation.entity.User;
import com.titleevaluation.repository.PermissionRepository;
import com.titleevaluation.repository.RoleRepository;
import com.titleevaluation.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;

@Component
public class DataInitializer implements CommandLineRunner {

    private final RoleRepository roleRepository;
    private final PermissionRepository permissionRepository;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public DataInitializer(RoleRepository roleRepository, PermissionRepository permissionRepository, 
                          UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.roleRepository = roleRepository;
        this.permissionRepository = permissionRepository;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void run(String... args) throws Exception {
        // 创建权限
        Permission readPermission = createPermissionIfNotExists("READ", "读取权限");
        Permission writePermission = createPermissionIfNotExists("WRITE", "写入权限");
        Permission updatePermission = createPermissionIfNotExists("UPDATE", "更新权限");
        Permission deletePermission = createPermissionIfNotExists("DELETE", "删除权限");
        Permission approvePermission = createPermissionIfNotExists("APPROVE", "审批权限");
        Permission managePermission = createPermissionIfNotExists("MANAGE", "管理权限");

        // 创建角色
        Role clientRole = createRoleIfNotExists("客户", "客户角色", 
            new HashSet<>(Arrays.asList(readPermission, writePermission)));
        
        Role memberRole = createRoleIfNotExists("组员", "组员角色", 
            new HashSet<>(Arrays.asList(readPermission, writePermission, updatePermission)));
        
        Role leaderRole = createRoleIfNotExists("组长", "组长角色", 
            new HashSet<>(Arrays.asList(readPermission, writePermission, updatePermission, deletePermission)));
        
        Role managerRole = createRoleIfNotExists("业务部门经理", "业务部门经理角色", 
            new HashSet<>(Arrays.asList(readPermission, writePermission, updatePermission, deletePermission, approvePermission)));
        
        Role supervisorRole = createRoleIfNotExists("督导", "督导角色", 
            new HashSet<>(Arrays.asList(readPermission, writePermission, updatePermission, deletePermission, approvePermission)));
        
        Role generalManagerRole = createRoleIfNotExists("总经理", "总经理角色", 
            new HashSet<>(Arrays.asList(readPermission, writePermission, updatePermission, deletePermission, approvePermission, managePermission)));

        // 创建默认用户
        createUserIfNotExists("admin", "admin@example.com", "系统管理员", "admin123", generalManagerRole);
        createUserIfNotExists("client", "client@example.com", "客户用户", "client123", clientRole);
        createUserIfNotExists("member", "member@example.com", "组员用户", "member123", memberRole);
        createUserIfNotExists("leader", "leader@example.com", "组长用户", "leader123", leaderRole);
        createUserIfNotExists("manager", "manager@example.com", "经理用户", "manager123", managerRole);
        createUserIfNotExists("supervisor", "supervisor@example.com", "督导用户", "supervisor123", supervisorRole);
    }

    private Permission createPermissionIfNotExists(String name, String description) {
        return permissionRepository.findByName(name)
                .orElseGet(() -> {
                    Permission permission = new Permission();
                    permission.setName(name);
                    permission.setDescription(description);
                    permission.setCreatedAt(LocalDateTime.now());
                    permission.setUpdatedAt(LocalDateTime.now());
                    return permissionRepository.save(permission);
                });
    }

    private Role createRoleIfNotExists(String name, String description, HashSet<Permission> permissions) {
        return roleRepository.findByName(name)
                .orElseGet(() -> {
                    Role role = new Role();
                    role.setName(name);
                    role.setDescription(description);
                    role.setPermissions(permissions);
                    role.setCreatedAt(LocalDateTime.now());
                    role.setUpdatedAt(LocalDateTime.now());
                    return roleRepository.save(role);
                });
    }

    private User createUserIfNotExists(String username, String email, String fullName, String password, Role role) {
        return userRepository.findByUsername(username)
                .orElseGet(() -> {
                    User user = new User();
                    user.setUsername(username);
                    user.setEmail(email);
                    user.setFullName(fullName);
                    user.setPassword(passwordEncoder.encode(password));
                    user.setRole(role);
                    user.setCreatedAt(LocalDateTime.now());
                    user.setUpdatedAt(LocalDateTime.now());
                    return userRepository.save(user);
                });
    }
}

